package com.coocaa.ops.api.common.handler;

import com.coocaa.ops.api.common.model.ExceptionResponseModel;
import com.coocaa.ops.api.common.constant.ResponseCode;
import com.coocaa.ops.api.common.model.ResponseData;
import com.coocaa.ops.api.common.constant.ResponseMsg;
import com.coocaa.ops.api.common.util.ResponseUtil;
import com.coocaa.ops.common.tool.exception.BusinessException;
import com.coocaa.ops.common.tool.exception.ExceptionUtil;
import com.coocaa.ops.common.tool.exception.ParamsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tangminghong
 * @date 2020-06-18
 */
@Slf4j
public class ApiExceptionHandler {


    @ExceptionHandler(ParamsException.class)
    public ResponseData<ExceptionResponseModel> handleParamException(ParamsException e) {
        ExceptionResponseModel responseModel
                = new ExceptionResponseModel(e.getParam(), e.getErrMsg());
        //TODO 日志规范
        log.error(ResponseMsg.PARAM_ERROR);
        return ResponseUtil.render(ResponseCode.PARAM_ERROR
                , ResponseMsg.PARAM_ERROR, responseModel);
    }

    @ExceptionHandler(BusinessException.class)
    public ResponseData<ExceptionResponseModel> handleBusinessException(BusinessException e) {
        ExceptionResponseModel responseModel
                = new ExceptionResponseModel(e.getErrOpData(), e.getErrMsg());
        //TODO 日志规范
        return ResponseUtil.render(ResponseCode.BUSINESS_ERROR
                , ResponseMsg.BUSINESS_ERROR, responseModel);
    }

    @ExceptionHandler(Exception.class)
    public ResponseData<ExceptionResponseModel> handleException(Exception e) {
        e.getStackTrace();
        Map<String, Object> stackTrace = new HashMap<>(1);
        stackTrace.put("stackTrace", ExceptionUtil.getStackTraceAsString(e));
        ExceptionResponseModel responseModel
                = new ExceptionResponseModel(stackTrace, e.getMessage());
        //TODO 日志规范
        log.error(e.getMessage());
        e.printStackTrace();
        return ResponseUtil.render(ResponseCode.INTERNAL_ERROR
                , ResponseMsg.INTERNAL_ERROR, responseModel);
    }
}
